#!/usr/bin/env python3
"""
AI选股器 v2.0 - 专业增强版
集成多因子模型、技术指标、机器学习的高级选股系统
"""

import easyquotation
import logging
import time
import requests
import json
import numpy as np
from typing import Dict, List, Optional, Tuple
from dataclasses import dataclass
from enum import Enum
from datetime import datetime
import os

# 导入自定义模块
from .technical_indicators import TechnicalIndicatorCalculator
from .multi_factor_model import MultiFactorModel, StockFactorAnalysis, FactorType


class SelectionStrategy(Enum):
    """选股策略"""
    BALANCED = "均衡策略"
    GROWTH = "成长策略"
    VALUE = "价值策略"
    MOMENTUM = "动量策略"
    QUALITY = "质量策略"
    TECHNICAL = "技术策略"


class RiskLevel(Enum):
    """风险等级"""
    CONSERVATIVE = "保守型"
    MODERATE = "稳健型"
    AGGRESSIVE = "积极型"


@dataclass
class EnhancedStockInfo:
    """增强版股票信息"""
    code: str
    name: str
    price: float
    change_pct: float
    volume: int
    market_cap: float
    
    # 多因子分析结果
    factor_analysis: StockFactorAnalysis
    
    # 技术指标
    technical_signals: Dict[str, str]
    technical_strength: float
    
    # 综合评分
    overall_score: float
    recommendation: str
    confidence_level: float
    
    # 风险评估
    risk_score: float
    risk_level: RiskLevel
    
    # 预期收益
    expected_return_1w: float
    expected_return_1m: float


@dataclass
class EnhancedSelectionResult:
    """增强版选股结果"""
    strategy: SelectionStrategy
    selected_stocks: List[EnhancedStockInfo]
    market_analysis: Dict[str, any]
    factor_attribution: Dict[FactorType, float]
    risk_metrics: Dict[str, float]
    performance_forecast: Dict[str, float]
    selection_time: datetime
    
    # AI分析结果
    ai_insights: Optional[str] = None
    market_sentiment: Optional[str] = None


class AIStockSelectorV2:
    """AI选股器 v2.0 - 专业增强版"""
    
    def __init__(self, 
                 data_source: str = 'tencent',
                 strategy: SelectionStrategy = SelectionStrategy.BALANCED,
                 risk_tolerance: RiskLevel = RiskLevel.MODERATE,
                 use_ai: bool = True):
        
        self.data_source = data_source
        self.strategy = strategy
        self.risk_tolerance = risk_tolerance
        self.use_ai = use_ai
        
        self.logger = self._setup_logging()
        self.quotation = self._initialize_quotation()
        
        # 初始化分析模块
        self.technical_calculator = TechnicalIndicatorCalculator()
        self.multi_factor_model = self._create_multi_factor_model()
        
        # 初始化DeepSeek R1 AI
        self.deepseek_ai = self._initialize_deepseek_ai()
        
        # 股票池配置
        self.stock_universe = self._initialize_stock_universe()
        
        # 启动时进行股票名称校对
        self._perform_startup_stock_validation()
        
        self.logger.info(f"AI选股器v2.0初始化成功 - 策略:{strategy.value}, 风险:{risk_tolerance.value}")
    
    def _setup_logging(self) -> logging.Logger:
        """设置日志"""
        logger = logging.getLogger('AIStockSelectorV2')
        logger.setLevel(logging.INFO)
        if not logger.handlers:
            handler = logging.StreamHandler()
            formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
            handler.setFormatter(formatter)
            logger.addHandler(handler)
        return logger
    
    def _initialize_quotation(self):
        """初始化行情接口"""
        try:
            if self.data_source == 'tencent':
                return easyquotation.use('tencent')
            else:
                return easyquotation.use('sina')
        except Exception as e:
            self.logger.error(f"初始化行情接口失败: {e}")
            return None
    
    def _initialize_deepseek_ai(self):
        """初始化DeepSeek R1 AI"""
        if not self.use_ai:
            return None
        
        try:
            # 导入DeepSeek AI类
            from .ai_stock_selector import DeepSeekAI
            
            # 优先使用R1推理模型
            try:
                ai = DeepSeekAI(model="deepseek-reasoner")
                self.logger.info("DeepSeek R1推理模型初始化成功")
                return ai
            except Exception as r1_error:
                self.logger.warning(f"DeepSeek R1推理模型初始化失败: {r1_error}, 尝试使用chat模型")
                ai = DeepSeekAI(model="deepseek-chat")
                self.logger.info("DeepSeek Chat模型初始化成功")
                return ai
                
        except Exception as e:
            self.logger.warning(f"DeepSeek AI初始化失败: {e}, 将使用传统算法")
            return None
    
    def _create_multi_factor_model(self) -> MultiFactorModel:
        """创建多因子模型"""
        # 根据策略调整因子权重
        if self.strategy == SelectionStrategy.GROWTH:
            factor_weights = {
                FactorType.GROWTH: 0.30,
                FactorType.MOMENTUM: 0.25,
                FactorType.TECHNICAL: 0.20,
                FactorType.FUNDAMENTAL: 0.15,
                FactorType.QUALITY: 0.10,
                FactorType.VALUE: 0.00  # 成长策略不重视价值因子
            }
        elif self.strategy == SelectionStrategy.VALUE:
            factor_weights = {
                FactorType.VALUE: 0.35,
                FactorType.FUNDAMENTAL: 0.25,
                FactorType.QUALITY: 0.20,
                FactorType.TECHNICAL: 0.15,
                FactorType.MOMENTUM: 0.05,
                FactorType.GROWTH: 0.00  # 价值策略不重视成长因子
            }
        elif self.strategy == SelectionStrategy.MOMENTUM:
            factor_weights = {
                FactorType.MOMENTUM: 0.40,
                FactorType.TECHNICAL: 0.30,
                FactorType.GROWTH: 0.15,
                FactorType.FUNDAMENTAL: 0.10,
                FactorType.QUALITY: 0.05,
                FactorType.VALUE: 0.00  # 动量策略不重视价值因子
            }
        elif self.strategy == SelectionStrategy.QUALITY:
            factor_weights = {
                FactorType.QUALITY: 0.35,
                FactorType.FUNDAMENTAL: 0.30,
                FactorType.VALUE: 0.20,
                FactorType.TECHNICAL: 0.10,
                FactorType.GROWTH: 0.05
            }
        elif self.strategy == SelectionStrategy.TECHNICAL:
            factor_weights = {
                FactorType.TECHNICAL: 0.50,
                FactorType.MOMENTUM: 0.30,
                FactorType.FUNDAMENTAL: 0.10,
                FactorType.QUALITY: 0.05,
                FactorType.VALUE: 0.05,
                FactorType.GROWTH: 0.00  # 技术策略不重视成长因子
            }
        else:  # BALANCED
            factor_weights = {
                FactorType.TECHNICAL: 0.25,
                FactorType.FUNDAMENTAL: 0.20,
                FactorType.MOMENTUM: 0.20,
                FactorType.VALUE: 0.15,
                FactorType.QUALITY: 0.10,
                FactorType.GROWTH: 0.10
            }
        
        return MultiFactorModel(factor_weights)
    
    def _initialize_stock_universe(self) -> Dict[str, List[str]]:
        """初始化股票池"""
        return {
            "大盘蓝筹": [
                "601611", "002162", "000858", "000895", "000596", "000568", "600036",
                "600000", "600519", "600276", "600887", "600585", "601166", "601318",
                "601398", "601288", "601988", "601939", "601012", "601857", "601668",
                "601818", "601088", "601328", "601766", "601225", "601211", "601899",
                "600519", "600036", "600276", "600887", "600585", "600028", "600036",
                "600048", "600104", "600111", "600196", "600309", "600406", "600438",
                "600519", "600547", "600570", "600703", "600745", "600837", "600900",
                "002304", "002415", "002456", "002475", "002594", "002601", "002714",
                "002736", "002142", "002230", "002371", "002460", "002624", "002653",
                "000858", "000895", "000596", "002304", "600519", "600887", "600779",
                "300059", "300124", "300142", "300274", "300347", "300408", "300433",
                "300628", "300750", "300760", "300763", "300896"
            ],
            "科技成长": [
                "000725", "002415", "002714", "300014", "300059", "300122", "300142",
                "300433", "300498", "300750", "688111", "688126", "688169", "688188"
            ],
            "新能源": [
                "002466", "300014", "300750", "603799", "688005", "688390", "002594",
                "300274", "002812", "300207", "300763", "300408", "002129", "300124"
            ],
            "医药生物": [
                "000661", "002821", "300015", "300122", "300347", "300601", "600196",
                "600276", "600521", "600867", "603259", "688139", "688180", "300760"
            ],
            "消费": [
                "000858", "000895", "000596", "002304", "600519", "600887", "600779",
                "603288", "002568", "300498", "000568", "002027", "600132", "000799"
            ]
        }
    
    def _perform_startup_stock_validation(self):
        """启动时进行股票名称校对"""
        try:
            self.logger.info("🔍 开始启动时股票名称校对...")
            
            # 读取配置文件中的股票代码
            config_stocks = self._load_config_stocks()
            if not config_stocks:
                self.logger.warning("未找到配置文件中的股票代码")
                return
            
            # 使用股票名称校对器进行批量校对
            from .stock_name_validator import get_stock_name_validator
            validator = get_stock_name_validator()
            validated_results = validator.batch_validate(config_stocks)
            
            # 生成校对报告
            report = validator.get_validation_report()
            
            # 输出校对结果
            self.logger.info(f"📊 股票名称校对完成 - 共校对 {report['total_validated']} 只股票")
            self.logger.info(f"   高置信度: {report['confidence_breakdown']['high']} 只")
            self.logger.info(f"   中置信度: {report['confidence_breakdown']['medium']} 只")
            self.logger.info(f"   低置信度: {report['confidence_breakdown']['low']} 只")
            
            # 报告有问题的股票
            if report.get('low_confidence_stocks'):
                self.logger.warning(f"⚠️  发现 {len(report['low_confidence_stocks'])} 只低置信度股票:")
                for stock in report['low_confidence_stocks']:
                    self.logger.warning(f"   {stock['code']}: {stock['name']} (置信度: {stock['confidence']:.2f})")
            
            # 显示准确识别的股票
            high_confidence_stocks = [
                (code, info.name) for code, info in validated_results.items() 
                if info.confidence >= 0.8
            ][:5]  # 只显示前5个
            
            if high_confidence_stocks:
                self.logger.info("✅ 部分准确识别的股票:")
                for code, name in high_confidence_stocks:
                    self.logger.info(f"   {code}: {name}")
                if len(validated_results) > 5:
                    self.logger.info(f"   ... 以及其他 {len(validated_results) - 5} 只股票")
            
        except Exception as e:
            self.logger.warning(f"启动时股票校对失败: {e}")
    
    def _load_config_stocks(self) -> List[str]:
        """从配置文件加载股票代码"""
        try:
            import yaml
            import os
            
            config_path = 'config/stocks.yaml'
            if not os.path.exists(config_path):
                self.logger.warning(f"配置文件不存在: {config_path}")
                return []
            
            with open(config_path, 'r', encoding='utf-8') as f:
                config = yaml.safe_load(f)
            
            a_stocks = config.get('a_stocks', [])
            stock_codes = []
            
            for stock_entry in a_stocks:
                if isinstance(stock_entry, str):
                    stock_code = stock_entry.strip().strip("'\"")
                    stock_codes.append(stock_code)
            
            return stock_codes
            
        except Exception as e:
            self.logger.error(f"加载配置文件失败: {e}")
            return []
    
    def intelligent_stock_selection(self, 
                                   max_selections: int = 10,
                                   min_score: float = 45.0,
                                   sector_filter: Optional[List[str]] = None) -> EnhancedSelectionResult:
        """智能选股主函数"""
        
        self.logger.info(f"开始智能选股分析 - 策略:{self.strategy.value}, 最大选择数:{max_selections}")
        
        try:
            # 1. 获取股票数据
            stock_data = self._fetch_stock_data(sector_filter)
            
            # 2. 多因子分析
            analyzed_stocks = self._perform_multi_factor_analysis(stock_data)
            
            # 3. 技术指标分析
            enhanced_stocks = self._enhance_with_technical_analysis(analyzed_stocks)
            
            # 4. 风险评估
            risk_assessed_stocks = self._perform_risk_assessment(enhanced_stocks)
            
            # 5. 策略筛选
            filtered_stocks = self._apply_strategy_filter(risk_assessed_stocks, min_score)
            
            # 6. 排序和选择
            selected_stocks = self._rank_and_select(filtered_stocks, max_selections)
            
            # 7. 生成分析报告
            result = self._generate_selection_result(selected_stocks, stock_data)
            
            self.logger.info(f"选股完成，共选出{len(selected_stocks)}只股票")
            
            return result
            
        except Exception as e:
            self.logger.error(f"智能选股失败: {e}")
            return self._get_default_result()
    
    def _fetch_stock_data(self, sector_filter: Optional[List[str]] = None) -> Dict[str, Dict]:
        """获取股票数据"""
        all_stocks = []
        
        # 确定要分析的股票池
        if sector_filter:
            for sector in sector_filter:
                if sector in self.stock_universe:
                    all_stocks.extend(self.stock_universe[sector])
        else:
            for stocks in self.stock_universe.values():
                all_stocks.extend(stocks)
        
        # 去重
        all_stocks = list(set(all_stocks))
        
        self.logger.info(f"正在获取{len(all_stocks)}只股票的行情数据...")
        
        try:
            if self.quotation:
                quotes = self.quotation.stocks(all_stocks)
                return quotes
            else:
                # 使用模拟数据进行演示
                return self._generate_mock_stock_data(all_stocks)
        except Exception as e:
            self.logger.warning(f"获取行情数据失败，使用模拟数据: {e}")
            return self._generate_mock_stock_data(all_stocks)
    
    def _generate_mock_stock_data(self, stock_codes: List[str]) -> Dict[str, Dict]:
        """生成模拟股票数据 - 集成股票名称校对功能"""
        mock_data = {}
        
        # 使用股票名称校对器进行二次校对
        try:
            from .stock_name_validator import get_stock_name_validator
            validator = get_stock_name_validator()
            validated_names = validator.batch_validate(stock_codes)
            
            # 生成校对报告
            report = validator.get_validation_report()
            if report.get("low_confidence_stocks"):
                self.logger.warning(f"发现 {len(report['low_confidence_stocks'])} 个低置信度股票名称")
                for stock in report['low_confidence_stocks']:
                    self.logger.warning(f"  {stock['code']}: {stock['name']} (置信度: {stock['confidence']})")
            
        except ImportError:
            self.logger.warning("股票名称校对器导入失败，使用后备方案")
            validated_names = {code: type('StockInfo', (), {'name': f'股票{code}'})() for code in stock_codes}
        
        for code in stock_codes:
            # 生成随机但合理的股票数据
            hash_val = hash(code) % 1000
            base_price = 10 + (hash_val % 100)
            
            # 获取校对后的股票名称
            stock_name = validated_names.get(code)
            if stock_name:
                name = stock_name.name
            else:
                name = f'股票{code}'
            
            mock_data[code] = {
                'name': name,
                'now': base_price + (hash_val % 20) / 10,
                'close': base_price,
                'open': base_price + (hash_val % 10 - 5) / 10,
                'high': base_price + (hash_val % 15) / 10,
                'low': base_price - (hash_val % 10) / 10,
                'volume': 1000000 + (hash_val % 5000000),
                'turnover': 100000000 + (hash_val % 500000000),
                'change': (hash_val % 20 - 10) / 10,
                'changepercent': (hash_val % 20 - 10) / 10
            }
        
        return mock_data
    
    def _perform_multi_factor_analysis(self, stock_data: Dict[str, Dict]) -> List[StockFactorAnalysis]:
        """执行多因子分析"""
        analyzed_stocks = []
        
        for stock_code, data in stock_data.items():
            try:
                # 生成历史价格数据（模拟）
                current_price = float(data.get('now', 10.0))
                price_data = self._generate_price_history(current_price, 60)
                volume_data = [int(data.get('volume', 1000000))] * len(price_data)  # 使用实际成交量
                
                # 执行多因子分析
                stock_name = data.get('name', f'股票{stock_code}')
                analysis = self.multi_factor_model.analyze_stock(
                    stock_code, stock_name, price_data, volume_data
                )
                
                # 添加额外信息到分析结果
                analysis.current_price = current_price
                analysis.change_pct = float(data.get('changepercent', 0.0))
                
                analyzed_stocks.append(analysis)
                
            except Exception as e:
                self.logger.warning(f"分析股票{stock_code}失败: {e}")
                continue
        
        return analyzed_stocks
    
    def _enhance_with_technical_analysis(self, analyzed_stocks: List[StockFactorAnalysis]) -> List[EnhancedStockInfo]:
        """增强技术分析"""
        enhanced_stocks = []
        
        for analysis in analyzed_stocks:
            try:
                # 从分析结果中获取当前价格（如果有的话）
                current_price = getattr(analysis, 'current_price', 10.0)
                change_pct = getattr(analysis, 'change_pct', 0.0)
                price_data = self._generate_price_history(current_price, 30)
                volume_data = [1000000] * len(price_data)
                
                # 计算技术指标
                indicators = self.technical_calculator.calculate_all_indicators(
                    price_data, volume_data
                )
                
                # 提取技术信号
                technical_signals = {
                    name: indicator.signal 
                    for name, indicator in indicators.items()
                }
                
                # 计算技术强度
                signal_strength, _, _ = self.technical_calculator.get_comprehensive_signal(indicators)
                technical_strength = self._convert_signal_to_score(signal_strength)
                
                # 创建增强股票信息
                enhanced_stock = EnhancedStockInfo(
                    code=analysis.stock_code,
                    name=analysis.stock_name,
                    price=current_price,
                    change_pct=change_pct,
                    volume=1000000,  # 简化
                    market_cap=current_price * 1000000,  # 简化市值计算
                    factor_analysis=analysis,
                    technical_signals=technical_signals,
                    technical_strength=technical_strength,
                    overall_score=analysis.overall_score,
                    recommendation=analysis.recommendation,
                    confidence_level=analysis.confidence_level,
                    risk_score=0.0,  # 待计算
                    risk_level=RiskLevel.MODERATE,  # 待计算
                    expected_return_1w=0.0,  # 待计算
                    expected_return_1m=0.0   # 待计算
                )
                
                enhanced_stocks.append(enhanced_stock)
                
            except Exception as e:
                self.logger.warning(f"技术分析增强失败 {analysis.stock_code}: {e}")
                continue
        
        return enhanced_stocks
    
    def _perform_risk_assessment(self, enhanced_stocks: List[EnhancedStockInfo]) -> List[EnhancedStockInfo]:
        """执行风险评估"""
        for stock in enhanced_stocks:
            try:
                # 计算风险得分
                risk_factors = []
                
                # 技术风险
                if stock.technical_strength < 30:
                    risk_factors.append(20)
                
                # 估值风险
                fundamental_score = stock.factor_analysis.factor_scores.get(
                    FactorType.FUNDAMENTAL, None
                )
                if fundamental_score and fundamental_score.score < 40:
                    risk_factors.append(15)
                
                # 流动性风险（简化）
                if stock.volume < 500000:
                    risk_factors.append(10)
                
                # 波动性风险（基于技术指标）
                atr_signal = stock.technical_signals.get('ATR', '持有')
                if '高波动' in str(atr_signal):
                    risk_factors.append(15)
                
                # 计算总风险得分
                total_risk = sum(risk_factors)
                stock.risk_score = min(100, total_risk)
                
                # 确定风险等级
                if total_risk <= 20:
                    stock.risk_level = RiskLevel.CONSERVATIVE
                elif total_risk <= 40:
                    stock.risk_level = RiskLevel.MODERATE
                else:
                    stock.risk_level = RiskLevel.AGGRESSIVE
                
                # 预期收益估算（简化模型）
                momentum_score = stock.factor_analysis.factor_scores.get(
                    FactorType.MOMENTUM, None
                )
                if momentum_score:
                    base_return = (momentum_score.score - 50) / 100  # -0.5 to 0.5
                    stock.expected_return_1w = base_return * 0.02  # 2%最大周收益
                    stock.expected_return_1m = base_return * 0.08  # 8%最大月收益
                
            except Exception as e:
                self.logger.warning(f"风险评估失败 {stock.code}: {e}")
                stock.risk_score = 50.0
                stock.risk_level = RiskLevel.MODERATE
        
        return enhanced_stocks
    
    def _apply_strategy_filter(self, stocks: List[EnhancedStockInfo], min_score: float) -> List[EnhancedStockInfo]:
        """应用策略筛选"""
        filtered_stocks = []
        
        for stock in stocks:
            # 基础分数筛选
            if stock.overall_score < min_score:
                continue
            
            # 风险偏好筛选
            if self.risk_tolerance == RiskLevel.CONSERVATIVE and stock.risk_level == RiskLevel.AGGRESSIVE:
                continue
            elif self.risk_tolerance == RiskLevel.MODERATE and stock.risk_level == RiskLevel.AGGRESSIVE:
                # 适度风险可接受高风险，但要求更高分数
                if stock.overall_score < min_score + 10:
                    continue
            
            # 策略特定筛选（进一步降低要求）
            if self.strategy == SelectionStrategy.GROWTH:
                growth_score = stock.factor_analysis.factor_scores.get(FactorType.GROWTH, None)
                if growth_score and growth_score.score < 25:  # 进一步降低成长策略的要求
                    continue
            elif self.strategy == SelectionStrategy.VALUE:
                value_score = stock.factor_analysis.factor_scores.get(FactorType.VALUE, None)
                if value_score and value_score.score < 30:  # 进一步降低价值策略的要求
                    continue
            elif self.strategy == SelectionStrategy.TECHNICAL:
                if stock.technical_strength < 25:  # 进一步降低技术策略的要求
                    continue
            
            filtered_stocks.append(stock)
        
        return filtered_stocks
    
    def _rank_and_select(self, stocks: List[EnhancedStockInfo], max_selections: int) -> List[EnhancedStockInfo]:
        """排序和选择"""
        # 根据策略调整排序权重
        def calculate_sort_score(stock: EnhancedStockInfo) -> float:
            base_score = stock.overall_score
            
            if self.strategy == SelectionStrategy.MOMENTUM:
                momentum_score = stock.factor_analysis.factor_scores.get(FactorType.MOMENTUM, None)
                if momentum_score:
                    base_score += momentum_score.score * 0.3
            elif self.strategy == SelectionStrategy.TECHNICAL:
                base_score += stock.technical_strength * 0.4
            elif self.strategy == SelectionStrategy.QUALITY:
                quality_score = stock.factor_analysis.factor_scores.get(FactorType.QUALITY, None)
                if quality_score:
                    base_score += quality_score.score * 0.3
            
            # 风险调整
            base_score -= stock.risk_score * 0.1
            
            return base_score
        
        # 排序
        stocks.sort(key=calculate_sort_score, reverse=True)
        
        # 选择前N只
        return stocks[:max_selections]
    
    def _generate_selection_result(self, selected_stocks: List[EnhancedStockInfo], 
                                  all_stock_data: Dict[str, Dict]) -> EnhancedSelectionResult:
        """生成选股结果"""
        
        # 市场分析
        market_analysis = {
            "total_analyzed": len(all_stock_data),
            "selected_count": len(selected_stocks),
            "avg_score": np.mean([s.overall_score for s in selected_stocks]) if selected_stocks else 0,
            "strategy": self.strategy.value,
            "risk_tolerance": self.risk_tolerance.value
        }
        
        # 因子归因分析
        factor_attribution = {}
        if selected_stocks:
            for factor_type in FactorType:
                scores = []
                for stock in selected_stocks:
                    factor_score = stock.factor_analysis.factor_scores.get(factor_type, None)
                    if factor_score:
                        scores.append(factor_score.score)
                if scores:
                    factor_attribution[factor_type] = np.mean(scores)
        
        # 风险指标
        risk_metrics = {}
        if selected_stocks:
            risk_metrics = {
                "avg_risk_score": np.mean([s.risk_score for s in selected_stocks]),
                "max_risk_score": np.max([s.risk_score for s in selected_stocks]),
                "conservative_count": sum(1 for s in selected_stocks if s.risk_level == RiskLevel.CONSERVATIVE),
                "moderate_count": sum(1 for s in selected_stocks if s.risk_level == RiskLevel.MODERATE),
                "aggressive_count": sum(1 for s in selected_stocks if s.risk_level == RiskLevel.AGGRESSIVE)
            }
        
        # 业绩预测
        performance_forecast = {}
        if selected_stocks:
            performance_forecast = {
                "expected_return_1w": np.mean([s.expected_return_1w for s in selected_stocks]),
                "expected_return_1m": np.mean([s.expected_return_1m for s in selected_stocks]),
                "win_rate_estimate": min(85, 50 + np.mean([s.overall_score for s in selected_stocks]) * 0.5)
            }
        
        return EnhancedSelectionResult(
            strategy=self.strategy,
            selected_stocks=selected_stocks,
            market_analysis=market_analysis,
            factor_attribution=factor_attribution,
            risk_metrics=risk_metrics,
            performance_forecast=performance_forecast,
            selection_time=datetime.now(),
            ai_insights=self._generate_ai_insights(selected_stocks),
            market_sentiment="中性"  # 简化
        )
    
    def _generate_ai_insights(self, selected_stocks: List[EnhancedStockInfo]) -> str:
        """生成AI洞察 - 集成DeepSeek R1分析"""
        if not selected_stocks:
            if self.deepseek_ai:
                return self._get_deepseek_no_stocks_analysis()
            return "未找到符合条件的股票"
        
        # 基础分析
        avg_score = np.mean([s.overall_score for s in selected_stocks])
        
        basic_insights = [
            f"基于{self.strategy.value}策略，共筛选出{len(selected_stocks)}只优质标的。",
            f"组合平均得分{avg_score:.1f}分，整体质量{'优秀' if avg_score >= 70 else '良好' if avg_score >= 60 else '一般'}。"
        ]
        
        # 分析主要因子特征
        best_factors = []
        for factor_type, score in self._get_top_factors(selected_stocks):
            if score >= 65:
                best_factors.append(factor_type.value)
        
        if best_factors:
            basic_insights.append(f"组合在{', '.join(best_factors[:2])}方面表现突出。")
        
        # 风险提示
        high_risk_count = sum(1 for s in selected_stocks if s.risk_level == RiskLevel.AGGRESSIVE)
        if high_risk_count > len(selected_stocks) * 0.3:
            basic_insights.append("注意：组合中高风险标的占比较高，建议关注风险控制。")
        
        basic_analysis = " ".join(basic_insights)
        
        # 如果启用了DeepSeek AI，进行深度分析
        if self.deepseek_ai:
            try:
                enhanced_analysis = self._get_deepseek_portfolio_analysis(selected_stocks)
                if enhanced_analysis:
                    return f"{basic_analysis}\n\n🤖 DeepSeek R1深度分析: {enhanced_analysis}"
            except Exception as e:
                self.logger.warning(f"DeepSeek AI分析失败: {e}")
        
        return basic_analysis
    
    def _get_deepseek_portfolio_analysis(self, selected_stocks: List[EnhancedStockInfo]) -> str:
        """使用DeepSeek R1分析投资组合"""
        try:
            # 构建组合数据
            portfolio_data = {
                "strategy": self.strategy.value,
                "risk_tolerance": self.risk_tolerance.value,
                "stock_count": len(selected_stocks),
                "avg_score": np.mean([s.overall_score for s in selected_stocks]),
                "stocks": []
            }
            
            for stock in selected_stocks:
                stock_info = {
                    "name": stock.name,
                    "code": stock.code,
                    "score": stock.overall_score,
                    "risk_level": stock.risk_level.value,
                    "technical_strength": stock.technical_strength,
                    "top_factors": []
                }
                
                # 添加主要因子信息
                for factor_type, factor_score in stock.factor_analysis.factor_scores.items():
                    if factor_score.score >= 60:
                        stock_info["top_factors"].append(f"{factor_type.value}({factor_score.score:.0f}分)")
                
                portfolio_data["stocks"].append(stock_info)
            
            # 创建DeepSeek分析提示
            prompt = self._create_portfolio_analysis_prompt(portfolio_data)
            
            # 调用DeepSeek API
            response = self.deepseek_ai._call_deepseek_api(prompt)
            
            # 解析响应
            return self._parse_portfolio_analysis(response)
            
        except Exception as e:
            self.logger.error(f"DeepSeek组合分析失败: {e}")
            return None
    
    def _create_portfolio_analysis_prompt(self, portfolio_data: Dict) -> str:
        """创建投资组合分析提示词"""
        prompt = f"""
作为资深的量化投资专家，请对以下A股投资组合进行专业分析：

投资组合概况:
- 选股策略: {portfolio_data['strategy']}
- 风险偏好: {portfolio_data['risk_tolerance']}
- 股票数量: {portfolio_data['stock_count']}只
- 平均得分: {portfolio_data['avg_score']:.1f}分

组合成分股票:
"""
        
        for i, stock in enumerate(portfolio_data['stocks'], 1):
            factors_text = "、".join(stock['top_factors'][:3]) if stock['top_factors'] else "无突出因子"
            prompt += f"{i}. {stock['name']}({stock['code']}) - 综合{stock['score']:.0f}分, {stock['risk_level']}, 优势因子: {factors_text}\n"
        
        if self.deepseek_ai and self.deepseek_ai.reasoning_enabled:
            # R1模型使用更详细的分析要求
            prompt += """

请从以下专业角度进行深度分析:

1. **组合构成分析**: 评估股票选择的合理性和互补性
2. **风险收益评估**: 分析组合的风险收益特征
3. **因子暴露分析**: 评估组合在各投资因子上的暴露
4. **持仓建议**: 提供具体的仓位配置建议
5. **风险控制**: 识别主要风险点并提出控制措施

请用简洁的中文回复，重点突出关键洞察和实用建议。
"""
        else:
            # 传统模型使用简化要求
            prompt += """

请简要分析:
1. 组合质量评价
2. 主要风险提示
3. 投资建议

请用简洁的中文回复。
"""
        
        return prompt
    
    def _parse_portfolio_analysis(self, response: str) -> str:
        """解析DeepSeek组合分析结果"""
        try:
            # 清理和格式化响应
            analysis = response.strip()
            
            # 移除可能的格式化标记
            analysis = analysis.replace("**", "").replace("##", "")
            
            # 限制长度
            if len(analysis) > 300:
                analysis = analysis[:300] + "..."
            
            return analysis
            
        except Exception as e:
            self.logger.error(f"解析DeepSeek分析结果失败: {e}")
            return "AI分析解析失败"
    
    def _get_deepseek_no_stocks_analysis(self) -> str:
        """当没有选出股票时的DeepSeek分析"""
        try:
            prompt = f"""
作为资深投资专家，当前使用{self.strategy.value}策略和{self.risk_tolerance.value}风险偏好进行A股选股，但未找到符合条件的股票。

请简要分析可能的原因并提供建议：
1. 市场环境分析
2. 策略调整建议
3. 操作建议

请用简洁的中文回复。
"""
            
            response = self.deepseek_ai._call_deepseek_api(prompt)
            analysis = response.strip()[:200]
            return f"未找到符合条件的股票。{analysis}"
            
        except Exception as e:
            self.logger.error(f"DeepSeek无股票分析失败: {e}")
            return "未找到符合条件的股票，建议调整筛选条件或策略参数。"
    
    def _get_top_factors(self, stocks: List[EnhancedStockInfo]) -> List[Tuple[FactorType, float]]:
        """获取表现最好的因子"""
        factor_scores = {}
        
        for factor_type in FactorType:
            scores = []
            for stock in stocks:
                factor_score = stock.factor_analysis.factor_scores.get(factor_type, None)
                if factor_score:
                    scores.append(factor_score.score)
            if scores:
                factor_scores[factor_type] = np.mean(scores)
        
        return sorted(factor_scores.items(), key=lambda x: x[1], reverse=True)
    
    def _convert_signal_to_score(self, signal: str) -> float:
        """将信号转换为分数"""
        if signal == "买入":
            return 75.0
        elif signal == "卖出":
            return 25.0
        else:
            return 50.0
    
    def _generate_price_history(self, current_price: float, days: int) -> List[float]:
        """生成模拟历史价格"""
        prices = []
        price = current_price * 0.9  # 起始价格
        
        for i in range(days):
            # 简单的随机游走
            change = np.random.normal(0, 0.02)  # 2%标准差
            price *= (1 + change)
            prices.append(price)
        
        return prices
    
    def _get_default_result(self) -> EnhancedSelectionResult:
        """获取默认结果"""
        return EnhancedSelectionResult(
            strategy=self.strategy,
            selected_stocks=[],
            market_analysis={"error": "数据获取失败"},
            factor_attribution={},
            risk_metrics={},
            performance_forecast={},
            selection_time=datetime.now(),
            ai_insights="数据获取失败，无法进行分析",
            market_sentiment="未知"
        )
    
    def display_selection_result(self, result: EnhancedSelectionResult):
        """显示选股结果"""
        print(f"\n{'='*100}")
        print(f"🚀 AI选股器v2.0 - 专业分析报告")
        print(f"{'='*100}")
        
        print(f"\n📊 选股策略: {result.strategy.value}")
        print(f"⏰ 分析时间: {result.selection_time.strftime('%Y-%m-%d %H:%M:%S')}")
        print(f"🎯 选股数量: {len(result.selected_stocks)}")
        
        if result.ai_insights:
            print(f"\n🤖 AI洞察: {result.ai_insights}")
        
        # 显示选中的股票
        if result.selected_stocks:
            print(f"\n📈 推荐股票列表:")
            print(f"{'排名':<4} {'代码':<8} {'名称':<12} {'综合得分':<8} {'推荐等级':<8} {'风险等级':<8} {'置信度':<8}")
            print(f"{'-'*80}")
            
            for i, stock in enumerate(result.selected_stocks, 1):
                print(f"{i:<4} {stock.code:<8} {stock.name:<12} {stock.overall_score:<8.1f} "
                      f"{stock.recommendation:<8} {stock.risk_level.value:<8} {stock.confidence_level:<8.1f}%")
        
        # 显示因子归因
        if result.factor_attribution:
            print(f"\n📋 因子表现分析:")
            sorted_factors = sorted(result.factor_attribution.items(), key=lambda x: x[1], reverse=True)
            for factor_type, score in sorted_factors:
                print(f"   {factor_type.value}: {score:.1f}/100")
        
        # 显示风险指标
        if result.risk_metrics:
            print(f"\n⚠️  风险分析:")
            print(f"   平均风险得分: {result.risk_metrics.get('avg_risk_score', 0):.1f}")
            print(f"   保守型: {result.risk_metrics.get('conservative_count', 0)}只")
            print(f"   稳健型: {result.risk_metrics.get('moderate_count', 0)}只")
            print(f"   积极型: {result.risk_metrics.get('aggressive_count', 0)}只")
        
        # 显示业绩预测
        if result.performance_forecast:
            print(f"\n📈 业绩预测:")
            print(f"   预期周收益: {result.performance_forecast.get('expected_return_1w', 0)*100:+.1f}%")
            print(f"   预期月收益: {result.performance_forecast.get('expected_return_1m', 0)*100:+.1f}%")
            print(f"   胜率预估: {result.performance_forecast.get('win_rate_estimate', 50):.1f}%")
        
        print(f"\n{'='*100}")
        print("📢 免责声明：以上分析仅供参考，投资有风险，入市需谨慎！")
        print(f"{'='*100}")


def create_ai_selector_v2(data_source: str = 'tencent',
                         strategy: SelectionStrategy = SelectionStrategy.BALANCED,
                         risk_tolerance: RiskLevel = RiskLevel.MODERATE,
                         use_ai: bool = True) -> AIStockSelectorV2:
    """创建AI选股器v2.0实例"""
    return AIStockSelectorV2(data_source, strategy, risk_tolerance, use_ai)


if __name__ == "__main__":
    # 测试AI选股器v2.0
    selector = create_ai_selector_v2(
        strategy=SelectionStrategy.BALANCED,
        risk_tolerance=RiskLevel.MODERATE
    )
    
    result = selector.intelligent_stock_selection(max_selections=5)
    selector.display_selection_result(result) 